package com.module.frame.base

import android.content.Intent
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.module.frame.dialog.LoadingDialogUtils
import com.module.frame.ext.loadDialogShareFlow
import com.module.frame.ext.observe

/**
 * mvvm 基类，主要处理ViewDataBinding试图绑定
 * 加载框处理
 */
abstract class BaseVmVdbActivity<VM : BaseFrameViewModel, DB : ViewDataBinding> :
    BaseVmActivity<VM>() {
    open lateinit var mDatabind: DB

    /**
     * 通用加载框，代理类
     */
    val load: LoadingDialogUtils by lazy {
        LoadingDialogUtils()
    }

    /**
     * 试图获取
     */
    override fun getLayoutView(): View? {
        return try {
            mDatabind = try {
                inflateBindingWithGeneric(1,layoutInflater)!!
            } catch (e: Exception) {
                DataBindingUtil.setContentView(this, getLayoutId())
            }
            mDatabind.root
        } catch (e: Exception) {
            null
        }
    }

    override fun getLayoutId(): Int {
        return 0
    }

    override fun getIntent(intent: Intent) {
    }

    override fun initView() {
        super.initView()

    }

    override fun initListener() {
        /**
         * 加载框监听,全局
         */
        observe(loadDialogShareFlow) {
            if (it) {
                showLoading()
            } else {
                hideLoading()
            }
        }
        /**
         * 加载框监听,限制mViewModel
         */
        observe(mViewModel.loadDialogShareFlow) {
            if (it) {
                showLoading()
            } else {
                hideLoading()
            }
        }
    }

    override fun initData() {
    }

    /**
     * 显示加载框
     */
    open fun showLoading() {
        if (isFinishing) {
            return
        }
        load.show(this)
    }

    /**
     * 隐藏加载框
     */
    open fun hideLoading() {
        if (isFinishing) {
            return
        }
        load.hide()
    }

}